package config

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

// NewGorm 创建DB实例
func NewGorm(conf *Config) (db *gorm.DB, err error) {
	db, err = gorm.Open(mysql.New(mysql.Config{
		DSN:                       conf.MySQL.DSN(), // data source name
		DefaultStringSize:         256,              // default size for string fields
		DisableDatetimePrecision:  true,             // disable datetime precision, which not supported before MySQL 5.6
		DontSupportRenameIndex:    true,             // drop & create when rename index, rename index not supported before MySQL 5.7, MariaDB
		DontSupportRenameColumn:   true,             // `change` when rename column, rename column not supported before MySQL 8, MariaDB
		SkipInitializeWithVersion: true,             // auto configure based on currently MySQL version
	}), &gorm.Config{})
	if err != nil {
		return
	}
	db.Logger = logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      false,       // 禁用彩色打印
		},
	)
	if conf.Gorm.Debug {
		db = db.Debug()
	}
	//db.SingularTable(true)
	sqlDB, err := db.DB()
	if err != nil {
		return
	}
	sqlDB.SetMaxIdleConns(conf.Gorm.MaxIdleConns)
	sqlDB.SetMaxOpenConns(conf.Gorm.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(time.Duration(conf.Gorm.MaxLifetime) * time.Second)
	return
}
